const app = getApp()
const i18n = require('../../utils/i18n/index')

Page({
  data: {
    banners: [],
    displayNews:[],
    supplyList: [],
    categories: [],
    types: [
      { id: '', name: '全部', name_en: 'All' },
      { id: 0, name: '供应', name_en: 'Supply' },
      { id: 1, name: '需求', name_en: 'Demand' }
    ],
    categoryIndex: -1,
    typeIndex: -1,
    page: 1,
    hasMore: true,
    loading: false,
    refreshing: false,
    keyword: '',
    cdnUrl: '',
    locale: 'zh_CN',
    t: {},
    currentTab: 'all',
    list: [],
    categoriesShow: false,
    isLoading: false,
    loadingNews: false,
    pageNews: 1,
    hasMoreNews: true,
  },

  onLoad() {
    wx.hideTabBar();
    this.setData({
      cdnUrl: app.globalData.cdnUrl
    })
    this.setI18nData()
    this.loadCategories()
    this.loadSupplyList()
    wx.hideTabBar(); // 隐藏 tabBar
    // 监听语言变更事件
    const self = this
    app.globalData.eventBus.on('localeChanged', function() {
      self.setI18nData()
      self.loadSupplyList()
    })
  },

  onUnload() {
    // 移除事件监听
    app.globalData.eventBus.off('localeChanged')
  },

  onShow() {
      /*
    const keyword = wx.getStorageSync('searchKeyword') || ''
    this.setData({
        keyword:keyword,
        page: 1,
        supplyList: []
      }, function() {
        this.loadSupplyList(true)
      })
      */
  },

  setI18nData() {
    this.setData({
      locale: i18n.getLocale(),
      t: {
        appname: i18n.t('common.appname'),
        welcome: i18n.t('index.welcome'),
        title: i18n.t('supply.title'),
        tabAll: i18n.t('supply.tabs.all'),
        tabSupply: i18n.t('supply.tabs.supply'),
        tabDemand: i18n.t('supply.tabs.demand'),
        searchPlaceholder: i18n.t('supply.searchPlaceholder'),
        categoryPlaceholder: i18n.t('supply.categoryPlaceholder'),
        typePlaceholder: i18n.t('supply.typePlaceholder'),
        loading: i18n.t('common.loading'),
        noMore: i18n.t('supply.noMore'),
        empty: i18n.t('supply.empty'),
        publish: i18n.t('supply.publish.btn'),
        loginRequired: i18n.t('supply.loginRequired'),
        newsSection: {
            title: i18n.t('index.newsSection.title'),
            titlegongxu: i18n.t('index.newsSection.titlegongxu'),
        }
      }
    })
  },

  // banner点击
  onBannerTap(e) {
    const { type,a_id,id } = e.currentTarget.dataset
    console.log(type)
    if (type == 0) {
        wx.navigateTo({
            url: `/pages/banner/banner?id=${id}`
          })
    }else if(type == 1) {
        wx.navigateTo({
            url: `/pages/supply/detail/detail?id=${a_id}`
          })
    } else if(type == 2) {
        if (!app.globalData.isLogin) {
            wx.showModal({
              title: i18n.t('common.confirm'),
              content: this.data.t.loginRequired,
              confirmText: i18n.t('mine.login'),
              success: function(res) {
                if (res.confirm) {
                  wx.navigateTo({
                    url: '/pages/mine/login/login'
                  })
                }
              }
            })
            return
        }
        wx.navigateTo({
            url: '/pages/supply/publish/publish'
          })
    } else if(type == 3) {
        wx.navigateTo({
            url: `/pages/intro/intro?id=${a_id}`
          })
    } 
    
  },

  onLanguageChange() {
    this.setI18nData()
    this.loadSupplyList()
  },

// 切换语言
onSwitchLang() {
    const newLocale = this.data.locale === 'zh_CN' ? 'en_US' : 'zh_CN'
    i18n.setLocale(newLocale)
    this.setI18nData()
    this.loadSupplyList()
      
      // 更新 tabBar
      wx.setTabBarItem({
        index: 0,
        text: newLocale=='en_US'?'home':'首页'
      });
      wx.setTabBarItem({
        index: 1,
        text: newLocale=='en_US'?'About':'关于大联盟'
      });
      wx.setTabBarItem({
        index: 2,
        text: newLocale=='en_US'?'Publish':'发布供需'
      });
      wx.setTabBarItem({
        index: 3,
        text: newLocale=='en_US'?'Member':'成员名单'
      });
      wx.setTabBarItem({
        index: 4,
        text: newLocale=='en_US'?'Mine':'我的'
      });
},

  // 加载分类数据
  loadCategories() {
    const self = this
    wx.request({
      url: app.globalData.baseUrl + 'public/categories',
      success: function(res) {
        if (res.data.code === 0) {
          const categories = res.data.data.categories
          categories.map(item => {
            item.show = false;
            return item;  
          })
          
          self.setData({
            categories: categories|| []
          })
        }
      }
    })
  },

  onNewsMore:function() {
    if (this.data.loadingNews) return

    const self = this
    this.setData({ loadingNews: true })
    const data = this.data

    wx.request({
        url: app.globalData.baseUrl + 'public/needs',
        data: {
          page_news: data.pageNews,
          locale: data.locale
        },
        success: function(res) {
          if (res.data.code === 0) {
            const list = res.data.data.news || []
            const newList = data.displayNews.concat(list)
            
            self.setData({
              hasMoreNews: list.length === 2,
              pageNews: data.pageNews + 1,
              displayNews: newList,
              isLoading: false
            })
            wx.showTabBar();
            wx.removeStorageSync('searchKeyword')
          }
        },
        complete: function() {
          self.setData({
            loadingNews: false,
            refreshing: false
          })
        }
      })
  },

  // 加载供需列表
  loadSupplyList: function(isRefresh) {
    if (this.data.loading) return

    const self = this
    this.setData({ loading: true })
    const data = this.data
    
    const categories = this.data.categories
    const category_ids = []
    categories.forEach(item => {
        if (item.show) {
            category_ids.push(item.id)
        }
    })

    wx.request({
      url: app.globalData.baseUrl + 'public/needs',
      data: {
        page: data.page,
        category_id: category_ids.join(','),
        type: data.typeIndex >= 0 ? data.types[data.typeIndex].id : '',
        keyword: data.keyword,
        locale: data.locale
      },
      success: function(res) {
        if (res.data.code === 0) {
          const list = res.data.data.needs || []
          const newList = isRefresh ? list : data.supplyList.concat(list)
          
          self.setData({
            supplyList: newList,
            hasMore: list.length === 10,
            page: isRefresh ? 1 : data.page + 1,
            banners: res.data.data.banners || [],
            displayNews: res.data.data.news || [],
            hasMoreNews:true,
            pageNews:2,
            isLoading: false
          })
          wx.showTabBar();
          wx.removeStorageSync('searchKeyword')
        }
      },
      complete: function() {
        self.setData({
          loading: false,
          refreshing: false
        })
      }
    })
  },

  // 搜索处理
  onSearch: function(e) {
    const self = this
    this.setData({
      keyword: e.detail.value,
      page: 1,
      supplyList: []
    }, function() {
      self.loadSupplyList(true)
    })
  },

  onCategoryShow: function(e) {
    this.setData({
        categoriesShow: !this.data.categoriesShow // 使用 setData() 来更新视图
      });
  },
  onCategorySelect: function(e) {
      const data = e.currentTarget.dataset
      const categories = this.data.categories
      categories[data.index].show = !categories[data.index].show
      this.setData({
          categories:categories
      })
  },
  // 分类选择处理
  onCategoryChange: function(e) {
    const self = this
    this.setData({
      page: 1,
      supplyList: [],
      categoriesShow: false
    }, function() {
      self.loadSupplyList(true)
    })
  },
  closeCategory:function(e) {
    this.setData({
        categoriesShow: false
    })
  },
  onCategoryReset: function(e) {
    const self = this
    const categories = this.data.categories
    categories.forEach(item => {
        item.show = false;
    })
    
    this.setData({
      page: 1,
      supplyList: [],
      categoriesShow: false,
      categories: categories
    }, function() {
      self.loadSupplyList(true)
    })
  },
  // 类型选择处理
  onTypeChange: function(e) {
    const self = this
    this.setData({
      typeIndex: Number(e.detail.value),
      page: 1,
      supplyList: [],
      categoriesShow: false,
    }, function() {
      self.loadSupplyList(true)
    })
  },

  // 加载更多
  onLoadMore: function() {
    if (this.data.hasMore && !this.data.loading) {
      this.loadSupplyList()
    }
  },

  // 下拉刷新
  onRefresh: function() {
    const self = this
    this.setData({
      refreshing: true,
      page: 1,
      supplyList: []
    }, function() {
      self.loadSupplyList(true)
    })
  },

  // 点击供需项
  onSupplyItemTap: function(e) {
    const id = e.currentTarget.dataset.id
    wx.navigateTo({
      url: '/pages/supply/detail/detail?id=' + id
    })
  },

  onNewsTap: function(e) {
    const id = e.currentTarget.dataset.id
    wx.navigateTo({
      url: '/pages/intro/intro?id=' + id
    })
  },

  // 点击发布
  onPublishTap: function() {
    const self = this
    if (!app.globalData.isLogin) {
      wx.showModal({
        title: i18n.t('common.confirm'),
        content: this.data.t.loginRequired,
        confirmText: i18n.t('mine.login'),
        success: function(res) {
          if (res.confirm) {
            wx.navigateTo({
              url: '/pages/mine/login/login'
            })
          }
        }
      })
      return
    }
    wx.navigateTo({
      url: '/pages/supply/publish/publish'
    })
  },

  // 切换标签
  switchTab: function(e) {
    const tab = e.currentTarget.dataset.tab
    this.setData({ currentTab: tab })
    this.loadList(tab)
  },

  // 加载列表数据
  loadList: function(tab) {
    const self = this
    if (!tab) tab = 'all'
    
    wx.request({
      url: app.globalData.baseUrl + 'supply/list',
      data: {
        type: tab
      },
      success: function(res) {
        if (res.data.code === 0) {
          self.setData({
            list: res.data.data || []
          })
        }
      }
    })
  },

  // 跳转到详情页
  goToDetail: function(e) {
    const id = e.currentTarget.dataset.id
    wx.navigateTo({
      url: '/pages/supply/detail/detail?id=' + id
    })
  },
  // 分享按钮点击
  onShareTap() {
    wx.showShareMenu({
      withShareTicket: true,
      menus: ['shareAppMessage', 'shareTimeline']
    })
  },

  // 分享
  onShareAppMessage() {
    return {
      title: i18n.t('common.appname'),
      path: `/pages/supply/supply`
    }
  },
  onShareTimeline() {
    return {
      title: i18n.t('common.appname'),
      path: `/pages/supply/supply`
    }
  }
}) 